#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Silent logging module for the collaborative filtering recommendation system.
This implementation maintains the logging infrastructure without creating files or terminal output.

Created on: 2025-04-18
Author: Nianqing Liu
"""

import os
import logging
from logging.handlers import RotatingFileHandler
import time


def setup_logger(log_dir="results/logs", log_level=logging.INFO, silent=False):
    """
    Configure and return a logger for the recommendation system.
    By default, this logger is silent (no files, no console output).

    Parameters:
    -----------
    log_dir : str
        Directory where log files would be stored (not used if silent=True).
    log_level : int
        Logging level (e.g., logging.DEBUG, logging.INFO).
    silent : bool
        If True, suppresses all output to files and console.

    Returns:
    --------
    logging.Logger
        Configured logger instance.
    """
    # Create a logger
    logger = logging.getLogger("recommendation_system")
    logger.setLevel(log_level)

    # Clear existing handlers (avoid duplicate logs)
    if logger.handlers:
        logger.handlers = []

    if silent:
        # Add a NullHandler to prevent "No handlers could be found" warnings
        logger.addHandler(logging.NullHandler())
    else:
        # Only create log directory if we're actually logging to files
        os.makedirs(log_dir, exist_ok=True)

        # Create a unique log filename with timestamp
        timestamp = time.strftime("%Y%m%d-%H%M%S")
        log_file = os.path.join(log_dir, f"recommender_{timestamp}.log")

        # File handler with rotation (max 10MB per file, keep 5 backup files)
        file_handler = RotatingFileHandler(
            log_file, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8"
        )
        file_handler.setLevel(log_level)

        # Console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(log_level)

        # Create formatter and add it to the handlers
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # Add handlers to the logger
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

    return logger


def get_logger():
    """
    Get the recommendation system logger.

    Returns:
    --------
    logging.Logger
        Logger instance (silent by default).
    """
    logger = logging.getLogger("recommendation_system")

    # If logger has no handlers, set up a default silent logger
    if not logger.handlers:
        return setup_logger(silent=True)

    return logger
